package com.shishuo.cms.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContext;

import com.shishuo.cms.constant.SystemConstant;
import com.shishuo.cms.entity.Admin;
import com.shishuo.cms.entity.MenuEntity;
import com.shishuo.cms.exception.AdminLoginException;
import com.shishuo.cms.exception.AuthException;
import com.shishuo.cms.service.MenuService;
import com.shishuo.cms.service.RoleMenuService;


public class AuthInterceptor extends HandlerInterceptorAdapter{
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private RoleMenuService roleMenuService;
	
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            
            //没有声明需要权限,或者声明不验证权限
                if(authPassport == null || authPassport.validate() == false)
                return true;
            else{
                //在这里实现自己的权限验证逻辑
                if(AdminLogin(request))//如果验证成功返回true（这里直接写false来模拟验证失败的处理）
                {
                	if (hasAuth(request))
					{
                    	return true;
					}else {
						if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
	        					.getHeader("X-Requested-With") != null && request
	        					.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
	                        //返回到登录界面
	                        response.sendRedirect("/admin/noAuth.htm");
	        			} else {// JSON格式返回
	        				RequestContext requestContext = new RequestContext(request);
	        				throw new AuthException(requestContext.getMessage("system.noAuth"));
	        			}
	                	return false;
					}
                }
                else//如果验证失败
                {
                	//判断是json请求还是html请求
                	if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
        					.getHeader("X-Requested-With") != null && request
        					.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
                        //返回到登录界面
                        response.sendRedirect("/admin/login.htm");
        			} else {// JSON格式返回
        				RequestContext requestContext = new RequestContext(request);
        				throw new AdminLoginException(requestContext.getMessage("system.noLogin"));
        			}
                	return false;
                }       
            }
        }
        else
            return true;   
     }
	/**
	 * 判断当前链接请求是否拥有权限。
	 * @param request
	 * @return
	 */
	private boolean hasAuth(HttpServletRequest request)
	{
		String url=request.getRequestURI();
		HttpSession session = request.getSession();
		Admin admin=(Admin) session.getAttribute(SystemConstant.SESSION_ADMIN);
		return roleMenuService.hasAuthByRoleIdAndUrl(admin.getRoleId(),url);
	}
	/**
	 * 判断管理员是否登陆状态
	 * @return
	 * @throws Exception 
	 */
	private boolean AdminLogin(HttpServletRequest request) throws Exception {
		saveUrlToMenu(request);
		HttpSession session = request.getSession();
		if (null!=session.getAttribute(SystemConstant.SESSION_ADMIN)) {
			return true;
		}
		return false;
	}
	
	
	private void saveUrlToMenu(HttpServletRequest request) throws Exception
	{
		String url=request.getRequestURI();
		if(!menuService.isExist(url)){
			MenuEntity entity=new MenuEntity();
			entity.setMenuName(url);
			entity.setMenuCode(url);
			entity.setMenuUrl(url);
			menuService.save(entity);
		}
	}
}
